package com.shirley.myserialportapp

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.shirley.serialportlib.entity.Device
import kotlinx.android.synthetic.main.item_serial_port_device.view.*

/**
 * Description:
 * Created by Shirley
 * Date: 2019/12/6 10:12
 */
class SerialPortDeviceAdapter(private val mData: ArrayList<Device>) : RecyclerView.Adapter<SerialPortDeviceAdapter.ViewHolder>(){

    private var mListener: OnItemClickListener? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_serial_port_device, parent, false))
    }

    override fun getItemCount(): Int = mData.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        with(holder.itemView) {
            tvName.text = mData[position].name
            tvPath.text = mData[position].file.absolutePath
            tvPermission.text = String.format(resources.getString(R.string.serial_port_device_permission),
                mData[position].file.canRead(), mData[position].file.canWrite(), mData[position].file.canExecute())
            layout.setOnClickListener { mListener?.onItemClick(mData[position]) }
        }
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view)

    interface OnItemClickListener{
        fun onItemClick(device: Device)
    }

    fun setOnItemClickListener(listener: OnItemClickListener) {
        mListener = listener
    }

}